<?php
declare(strict_types=1);

namespace app\admin\service;

use app\api\service\CommonService;
use app\common\model\FriendModel;
use app\common\model\GroupModel;

class RobotService extends CommonService
{
    /**获取机器人列表
     * @return mixed
     */
    public function getRobotList()
    {
        return json_decode($this->sendSGHttp($this->API_URL, ['event' => 'GetLoggedAccountList']), true);
    }

    /**获取微信好友列表
     * @return mixed
     */
    public function wxChatFriend()
    {
        return json_decode($this->sendSGHttp($this->API_URL, ['event' => 'GetFriendList', 'robot_wxid' => 'wxid_xmyit5wjvewv22']), true);
    }

    public function wxChatGroup()
    {
        return json_decode($this->sendSGHttp($this->API_URL, ['event' => 'GetGroupList']), true);
    }

    /**
     * @throws \think\db\exception\DbException
     */
    public function dbFriend(): array
    {
        $friendModel = new FriendModel();
        $data = $friendModel->getListData();
        if (!$data['data']) {
            $ret = $this->wxChatFriend();
            $insertData = array_merge($ret['data']);
            $res = $friendModel->insertAll($insertData);
            if (!$res) return errorJson('请求失败');
            return $this->dbFriend();
        }
        return $data;
    }

    public function dbGroup(): array
    {
        $groupModel = new GroupModel();
        $data = $groupModel->getGroupData();
        if (!$data['data']) {
            $ret = $this->wxChatGroup();
            $insertData = array_merge($ret['data']);
            $res = $groupModel->insertAll($insertData);
            if (!$res) return errorJson('请求失败');
            return $this->dbGroup();
        }
        return $data;
    }

    public function setGroup(array $params): array
    {
        $data = [
            'status' => $params['status'] ?? 1,
        ];
        if(!$params['id']) return errorJson('id不能为空');
        $ret = (new GroupModel())->where('id',$params['id'])->update($data);
        if(!$ret) return errorJson('修改失败');
        return successJson([],'修改成功');
    }

}